package com.ly.test;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Map;

/**
 * @Classname MyLRU
 * @Description TODO
 * @Date 2021/1/30 20:15
 * @Author 冷心影翼
 */
public class MyLRU {

    private int maxSize;
    private HashMap<Integer,Node> hashMap;
    private Node first;
    private Node last;

    public MyLRU(int maxSize) {
        this.maxSize = maxSize;
        hashMap = new HashMap<>();
    }

    public void put(Integer page,String cache) {
        Node node = hashMap.get(page);
        if(node == null) {
            if(hashMap.size() >= maxSize) {
                removeLast();
            }
            node = new Node();
            node.key = page;
        }
        node.val = cache;
        moveToFirst(node);
        hashMap.put(page,node);
    }

    public String get(Integer page) {
        Node node = hashMap.get(page);
        if(node == null) {
            return null;
        }
        moveToFirst(node);
        return node.val;
    }

    private void removeLast() {
        if(last != null) {
            hashMap.remove(last.key);
            last = last.pre;
            if(last!=null) {
                last.next = null;
            }else {
                first = null;
            }
        }
    }

    private void moveToFirst(Node node) {
        if(node == last) {
            last = last.pre;
        }
        if(first == null || last == null) {
            first = node;
            last = node;
        }
        node.next = first;
        first.pre = node;
        first = node;
        first.pre = null;
    }

    class Node{
        Node next;
        Node pre;
        Integer key;
        String val;
    }


    public static void main(String[] args) {
        MyLRU myLRU = new MyLRU(3);
        myLRU.put(1,"a");
        myLRU.put(2,"b");
        myLRU.put(3,"c");
        myLRU.get(1);
        myLRU.get(2);
        myLRU.put(4,"d");
        myLRU.hashMap.forEach( (k,v)->{
            System.out.println(k+" "+v);
        });
    }
}
